import { api, util, dialog, forms, storage} from '../../../../js/util'; 
import { detail, scant } from '../../../../js/modules/mall';
const info = require("../../../../js/modules/info.js");
import { config } from "../../../../js/modules/gloab.js";
import BasePage from '../../../../js/common/base-page';
var app = getApp();
BasePage({
  pageKey:"scantGoods",

  /**
   * 页面的初始数据
   */
  data: {
    tablist: ['全部', '有货',  '无货'],
    tabIndex: 0,
    PageIndex: 1,
    PageSize: 20,
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    Currency: api.Currency || '￥',
    sortField: "AddTime",
    sortDirect: "desc",
    keywords: "",
    startTime: "",
    endTime: "",
    showInStock: -1,
    currentDate:'',
    showFilter: false, //是否显示筛选
    goodsList: [],
    hasMoreData: true, 
    showScantyText: true,
    quantityDigits: 0,
    priceDigits:2,
    GoodsUnitDisplayMode:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    let current = new Date();
    let year = current.getFullYear(),
        month = current.getMonth()+1,
        day = current.getDate();
    this.setData({
      currentDate:year+'-'+month+'-'+day
    });
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    config.getWholesaleConfigs(
    fkid,
    fkflag,
    "Wholesale",
      (model)=> {
        that.setData({
          quantityDigits: model.QuantityDigits,
          priceDigits: model.PriceDigits,
          GoodsUnitDisplayMode: model.GoodsUnitDisplayMode
        });
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      PageIndex: 1
    });
    this.loadScantyList();
  },
  /**加载商品列表 */
  loadScantyList() {
    var that = this;
    var param = {
      PageIndex: that.data.PageIndex,
      PageSize: that.data.PageSize,
      keywords: that.data.keywords,
      startTime: that.data.startTime,
      endTime: that.data.endTime,
      showInStock: that.data.showInStock,
      sortField: that.data.sortField,
      sortDirect: that.data.sortDirect 
    };
    scant.loadScantyList(param, function (res) { 
      var datas = res.data;
      var contentlistTem = that.data.goodsList;
      if (that.data.PageIndex == 1) {
        contentlistTem = [];
      }
      if (res.count > 0) { 
        datas.map((item, index) => {
          //这里需要把原始值用另一个字段存下来，方便后面计算时用原始值计算
          item.SBuyLowerLimit = item.BuyLowerLimit || 0;
          item.SBuyUpperLimit = item.BuyUpperLimit || 0;
          item.SStock = item.Stock;
          let units = item.AuxiliaryUnits||[];
          that.unitList(units,item.UnitPrices,item.CartCount,item)
          item.show = false;
        });
        var goodlist = contentlistTem.concat(datas);
        if (goodlist.length < that.data.PageSize) {
          that.setData({
            goodsList: goodlist,
            hasMoreData: false
          });
        } else {
          that.setData({
            goodsList: goodlist,
            hasMoreData: true,
            PageIndex: that.data.PageIndex + 1
          });
        }

      } else {
        that.setData({
          goodsList: [],
          hasMoreData: true,
          PageIndex: 1
        });
      }
    }, this.data.isrefresh);
  },
  unitList(AuxiliaryUnits,UnitPrices,CartCount,goodlist){
    let { quantityDigits } = this.data;
    for(var i=0;i<AuxiliaryUnits.length;i++){
      var item = AuxiliaryUnits[i];
      var t = detail.parseRule(UnitPrices, item.Translated, item.Qty || 0, false);
      if(t.has){
        item.price = t.price;
        if(t.integral){
          item.integral = t.integral;
        }
      }
      var otherAuxiliaryUnits = AuxiliaryUnits.filter(unit=>{return unit.Translated != item.Translated});
      var otherUnitQuantity = 0;
      if (otherAuxiliaryUnits&&otherAuxiliaryUnits.length>0) {
          otherAuxiliaryUnits.map((child, idx) => {
              if (child.Qty!=undefined&&child.Qty>0) {
                  otherUnitQuantity += (child.Qty || 0) * (child.Translated || 1);
              }
          });
      }
      item.BuyLowerLimit = goodlist.SBuyLowerLimit > 0 && goodlist.SBuyLowerLimit > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SBuyLowerLimit - otherUnitQuantity, quantityDigits) : 0;
      item.BuyUpperLimit = goodlist.SBuyUpperLimit > 0 && goodlist.SBuyUpperLimit > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SBuyUpperLimit - otherUnitQuantity, quantityDigits) : 0;
      item.Stock = goodlist.SStock > 0 && goodlist.SStock > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SStock - otherUnitQuantity, quantityDigits) : 0;
      item.IsSingle = goodlist.IsSingle;
      item.DefaultUnit = item.Name;
      item.ZeroStockBuy = goodlist.ZeroStockBuy;
      item.SpecValue = goodlist.SpecValue;
      item.ProductId = goodlist.ProductId;
      item.DiscountId = goodlist.DiscountId;
      item.DiscountType = goodlist.DiscountType;
      AuxiliaryUnits[i] = item;
      if(this.data.GoodsUnitDisplayMode == 0&&item.Translated == (goodlist.Translated||goodlist.Radix)){
        goodlist.BuyLowerLimit = item.BuyLowerLimit;
        goodlist.BuyUpperLimit = item.BuyUpperLimit;
        goodlist.Stock = item.Stock;
      }
    }
  },
  bindScan(){
    var that = this;
    wx.scanCode({
      success: (res) => {
        that.data.keywords = res.result;
        that.data.PageIndex = 1;
        that.loadScantyList();
      }
    })
  },
  /**搜索 */
  bindSearch(e){
    this.data.keywords = e.detail;
    this.data.PageIndex = 1;
    this.loadScantyList();
  },
  /**
   * 切换当前选择项
   */
  onSwitchTab: function(res) {
    var that = this;
    let { tabIndex } = this.data;
    if (tabIndex == res.detail.currentNum.id) return;
    tabIndex = parseInt(res.detail.currentNum.id);
    this.setData({
      tabIndex: tabIndex,
      showInStock: tabIndex == 2 ? 0 : tabIndex == 1 ? 1 : -1,
      PageIndex: 1
    }, () => {
      that.loadScantyList();
    });
  },
  /**
   * 选择日期
   */
  bindDateChange: function(e) {
    let dateType = e.currentTarget.dataset.type
    this.setData({
      [dateType]: e.detail.value
    })
  },
  bindInputChange:function(e){
    this.setData({
      keywords: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
* 页面相关事件处理函数--监听用户下拉动作
*/
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    this.data.PageIndex = 1;
    this.loadScantyList();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function (e) {
    if (this.data.hasMoreData) { 
      this.loadScantyList();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  
  /**
   * 点击筛选
   */
  onFilterEvent(e) {
    this.setData({
      showFilter: true
    });
  },
  /**
  * 确定
  */
  confirm:function(){
    var that = this;
    this.setData({
      showFilter: false,
      PageIndex: 1
    }, () => {
      that.loadScantyList();
    });
  },
  /**
  * 重置
  */
  reset:function(){
    this.setData({
      keywords: "",
      startTime: "",
      endTime: ""
    })
  },
  /**
  * 关闭筛选
  */
  shutFilter: function() {
    this.setData({
      showFilter: false
    });
  },
  /*
  * 表单值绑定
  */
  bindFormValue: function (e) {
    e = e.detail;
    this.data[e.target.id] = e.detail.value;

  },
 
  /**提交缺货登记 */
  saveScant() {
    //验证商品名称
    var scantyProductName = this.data.ScantyProductName;
    if (scantyProductName.length == 0) {
      util.alert("请输入商品名称");
      return;
    }
    //验证手机号
    var mobile = this.data.ScantyMobile;
    var mobileItem = {
      value: util.trim(mobile),
      validate: "isnull|mobile",
      error: "请输入正确的手机号"
    }
    if (!forms.validate(mobileItem)) return false;
    //验证验证码 
    var picvalidatecode = this.data.PicVerifyCode;
    if (picvalidatecode.length == 0) {
      util.alert("请先输入4位验证码");
      return;
    }
    var codeToken = storage.get("pic_verify_code");
    if (codeToken == undefined || codeToken.length == 0) {
      util.alert("图片验证码过期");
      return;
    }
    var param = {
      ProductId: 0,
      GoodsId: 0,
      BrandId: 0,
      ProductName: scantyProductName,
      Mobile: mobile,
      VerifyCode: picvalidatecode,
      CodeToken: codeToken
    }
    var that = this;
    scant.saveScanty(param, function (r) {
      util.alert(r.Message);
      if (r.Success) {
        that.data.PageIndex=1;
        that.loadScantyList();
      }
    });
  },
  /**删除缺货登记记录 */
  removeScanty(e){
    var id = e.detail.id;
    var param = {
      scantyId: id 
    }
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否删除？',
      success:function(res){
        if(res.confirm){
          scant.removeScanty(param, function (r) {
            util.alert(r.Message);
            if (r.Success) {
              that.data.PageIndex = 1;
              that.loadScantyList();
            }
          });
        }else{
          return;
        }
      }
    })
  },
  onUnload: function (e) {
    this.data.pre_page = this.getPreData();
    this.data.pre_page.data.isBack = true;
  },
  getPreData: function () {
    const pages = getCurrentPages();
    const length = pages.length;
    const prePage = pages[length - 2]; //上一页
    return prePage;
  },
  bindUnfold(e){
    var that = this;
    var index = e.currentTarget.dataset.index;
    that.data.goodsList[index].show=!that.data.goodsList[index].show;
    that.setData({
      goodsList:that.data.goodsList
    })
  },
  /**
   * 加入完成后调用，更新界面显示数量
   */
  onAddCartCompleted(e) {
    var that = this;
    e = e.detail;
    that.data.goodsList[e.idx] = e.product;
    that.setData({
      goodsList:that.data.goodsList
    });
  },
  /**显示多规则 */
  onShowGoodsModal(e) {
    // console.log(e,'====');
  },
})